package com.feihua.starter.web.modules.hdb.mvc;

import com.feihua.framework.rest.modules.common.mvc.BaseController;
import com.feihua.starter.comm.wx.ProgramMsgData;
import com.feihua.starter.comm.qq.weixin.mp.aes.AesException;
import com.feihua.utils.properties.PropertiesUtils;
import org.apache.commons.io.IOUtils;
import com.feihua.starter.comm.qq.weixin.mp.aes.SHA1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * @Auther: wzn
 * @Date: 2018/8/15 11:13
 * @Description:
 */
@RestController
@RequestMapping("/wx-service")
public class WeixinController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(WeixinController.class);

    @RequestMapping(value = "program/{program}/push", produces = "application/xml;charset=UTF-8")
    public void push(HttpServletRequest request, HttpServletResponse response, ProgramMsgData progrramMsgData, @PathVariable String program) {
        InputStream inputStream = null;
        PrintWriter out = null;
        try {
            inputStream = request.getInputStream();
            out = response.getWriter();
            String postData = IOUtils.toString(inputStream, "UTF-8");
            logger.info("微信请求开始：request={},progrramMsgData={}", postData, progrramMsgData);
            String resultMsg = checkSignature(progrramMsgData, program);
            out.print(resultMsg);

        } catch (Exception e) {
            logger.error("Error occurs when process wechat request:", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
            if (out != null) try {
                out.close();
            } catch (Exception e) {}
        }
    }

    private String checkSignature(ProgramMsgData progrramMsgData, String program) {
        String token = PropertiesUtils.getProperty(String.format("miniprogram.%s.token", program));
        try {
            String signature = progrramMsgData.getSignature();
            String timestamp = progrramMsgData.getTimestamp();
            String nonce = progrramMsgData.getNonce();
            String sha1 = SHA1.get2SHA1(token, timestamp, nonce);
            logger.info("检验消息的真实性，并且获取解密后的明文：{}", sha1);
            if (signature.equals(sha1)) {
                return progrramMsgData.getEchostr();
            } else {
                return "";
            }

        } catch (AesException e) {
            logger.error(e.getMessage(), e);
        }
        return "";
    }
}
